using DiLe.Mes.Application.Common;
using DiLe.Mes.Application.Common.Mould;
using DiLe.Mes.Application.Handler;
using DiLe.Mes.Model.Common.Mould.Entity.Info;
using Microsoft.AspNetCore.Authorization;
using MiniExcelLibs;
using MiniExcelLibs.OpenXml;

namespace DiLe.Mes.Cloud.Controllers.Mould.Info
{
    /// <summary>
    /// 模具档案
    /// </summary>
    [ApiExplorerSettings(GroupName = ApiCloudGroupConst.MouldManage)]
    public class MouldInfoController : ApiBaseController {
        private readonly MouldInfoClient _mouldInfoClient;
        private readonly MouldExjosnHandler _handler;
        private readonly SystemClient _systemClient;
        private readonly OrganizationClient _organizationClient;
        /// <summary>
        /// 构造函数
        /// </summary>
        public MouldInfoController(MouldInfoClient mouldInfo,
                                   MouldExjosnHandler handler,
                                   SystemClient systemClient,
                                   OrganizationClient organizationClient) {
            _mouldInfoClient = mouldInfo;
            _handler = handler;
            _systemClient = systemClient;
            _organizationClient = organizationClient;
        }
        /// <summary>
        /// 获取模具档案列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetMouldInfoList(MouldInfoQueryParameter parameter) {
            var whereExpression = Expressionable.Create<MouldInfoEntity>();
            if (!parameter.Keyword.IsNullOrEmpty()) {
                whereExpression.Or(p => p.Name.Contains(parameter.Keyword));
                whereExpression.Or(p => p.Code.Contains(parameter.Keyword));
            }

            if (parameter.TypeId > 0) {
                whereExpression.And(p => p.TypeId == parameter.TypeId);
            }
            if (parameter.StatusId > 0) {
                whereExpression.And(p => p.StatusId == parameter.StatusId);
            }
            if (parameter.PositionId > 0) {
                whereExpression.And(p => p.PositionId == parameter.PositionId);
            }

            if (parameter.Pagination == null) {
                var res = await _mouldInfoClient.GetMouldInfoListAsync(whereExpression.ToExpression());
                await _handler.FillMouldInfoExjosn(res);
                return Success(res);
            } else {
                var res = await _mouldInfoClient.GetMouldInfoPageListAsync(whereExpression.ToExpression(), parameter.Pagination);
                await _handler.FillMouldInfoExjosn(res.Record);
                return Success(res);
            }
        }
        /// <summary>
        /// 获取模具档案
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetMouldInfo(long id) {
            var res = await _mouldInfoClient.GetMouldInfoAsync(id);
            await _handler.FillMouldInfoExjosn(new List<MouldInfoEntity> { res });
            return Success(res);
        }
        /// <summary>
        /// 获取模具次数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<MouldInfoDto>> GetMouldNumber(MouldNumberParameter parameter) {
            var model = new MouldInfoDto();
            var res = await _mouldInfoClient.GetMouldInfoAsync(parameter.MouldId);
            await _handler.FillMouldInfoExjosn(new List<MouldInfoEntity> { res });
            model.Model = res;
            model.MouldNumData = new PaginationModel<MouldNumModel>();
            return Success(model);
        }



        /// <summary>
        /// 保存模具档案
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveMouldInfo(MouldInfoEntity entity) {
            var resId = await _mouldInfoClient.SaveMouldInfoAsync(entity);
            return resId > 0 ? Success() : Fail();
        }
        /// <summary>
        /// 删除模具档案
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DeleteMouldInfo(List<long> ids) {
            var res = await _mouldInfoClient.DeleteMouldInfoAsync(ids);
            return res ? Success() : Fail();
        }

        /// <summary>
        /// 上传模具档案
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UploadMouldInfo(IFormFile file) {
            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempfile");
            if (!Directory.Exists(dir)) {
                Directory.CreateDirectory(dir);
            }
            var filefullPath = Path.Combine(dir, file.FileName);
            using (FileStream fs = new(filefullPath, FileMode.Create)) {
                file.CopyTo(fs);
                fs.Flush();
            }
            var config = new OpenXmlConfiguration() {
                FillMergedCells = true
            };
            var rows = MiniExcel.Query(filefullPath, configuration: config).Cast<IDictionary<string, object>>();
            var headerRow = rows.FirstOrDefault();
            var maps = new List<(string key, string name)>();
            foreach (var key in headerRow!.Keys) {
                maps.Add((key, headerRow[key]?.ToString() ?? ""));
            }
            var rowDatas = rows.Skip(1).ToList();
            var statusList = await _mouldInfoClient.GetMouldStatusListAsync();
            var typeList = await _mouldInfoClient.GetMouldTypeListAsync();
            var organizationList = await _organizationClient.GetOrganizationListAsync();
            var userList = await _organizationClient.GetUserListAsync();

            var list = new List<MouldInfoEntity>();
            foreach (var rowData in rowDatas) {
                var m = new MouldInfoEntity();
                foreach (var (key, name) in maps) {
                    var value = rowData[key];
                    switch (name) {
                        case "模具名称":
                            m.Name = value?.ToString() ?? "";
                            break;
                        case "模具编码":
                            m.Code = value?.ToString() ?? "";
                            break;
                        case "模具类型":
                            var t = typeList?.FirstOrDefault(x => x.Name == value?.ToString());
                            m.TypeId = t?.Id ?? 0;
                            break;
                        case "当前状态":
                            var s = statusList?.FirstOrDefault(x => x.Name == value?.ToString());
                            m.StatusId = s?.Id ?? 0;
                            break;
                        case "所在工厂":
                            var f = organizationList?.FirstOrDefault(x => x.Name == value?.ToString());
                            m.FactoryId = f?.Id ?? 0;
                            break;
                        case "模具负责人":
                            var um = userList?.FirstOrDefault(x => x.Name == value?.ToString());
                            m.Manager = um?.Id ?? 0;
                            break;
                        case "操作员":
                            var u = userList?.FirstOrDefault(x => x.Name == value?.ToString());
                            m.Operator = u?.Id ?? 0;
                            break;
                        case "模具穴数":
                            string str = value?.ToString() ?? "";
                            m.CavityNum = str.Replace("穴", "")?.ToInt() ?? 0;
                            break;
                        default:
                            break;
                    }
                }
                list.Add(m);
            }
            foreach (var item in list) {
                item.MouldGroupCode = item.Code[..^3];
            }

            await _mouldInfoClient.InsertMouldInfoAsync(list);
            return Success();

        }
        /// <summary>
        /// 上传模具档案
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> UpdateMouldInfo() {
            var list = await _mouldInfoClient.GetMouldInfoListAsync();
            var maps = list.GroupBy(x => x.MouldGroupCode).Select(p => (p.Key, p.ToList())).ToList();

            var datas = new List<MouldInfoEntity>();
            foreach (var map in maps) {
                var count = map.Item2.FirstOrDefault()!.CavityNum;
                if (count == 1) {
                    continue;
                }
                foreach (var item in map.Item2) {
                    item.CavityNum = count / map.Item2.Count;
                    datas.Add(item);
                }

            }
            await _mouldInfoClient.UpdateMouldInfoAsync(datas);

            return Success();

        }


        /// <summary>
        /// 获取模具档案
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public async Task<ApiResult> GetMouldInfo222() {

            var list = await _mouldInfoClient.GetMouldInfoListAsync(p => p.TypeId == 471070917984325);
            foreach (var item in list) {
                item.LimitedNum = 400000;
                item.MouldLife = 500000;
            }
            await _mouldInfoClient.UpdateMouldInfoAsync(list);
            return Success();
        }


    }
}
